package com.xiaochi.practice.server.util;/**
 * @author zqx
 * @since 2024/7/20
 */

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util
 *
 * @author zqx
 * @since
 */
public class DruidEncrypUtil {

    private static String publicKey;

    private static String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            //私钥
            privateKey = keyPair[0];
            System.out.println("privateKey:" + privateKey);
            //公钥
            publicKey = keyPair[1];
            System.out.println("publicKey:" + publicKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    //加密
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }

    //解密
    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt:" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("1234");
        System.out.println("encrypt:" + encrypt);
        //使用 1.运行这个主方法
        //    2.获得加密后的密码
        //    3.代替原来的密码
        //原理：1.通过私钥加密 ”encrypt（）“ 明文密码”1234“
        //     2.把公钥写在配置文件里druid会使用这个来解密
        //
    }
}
